// UDP fragmentation and reassembly

use std::collections::HashMap;
use std::time::{Duration, Instant};

const MAX_FRAG_SIZE: usize = 1200;
const FRAG_TIMEOUT: Duration = Duration::from_secs(10);

#[derive(Debug, Clone)]
pub struct Fragment {
    pub id: u16,
    pub index: u8,
    pub total: u8,
    pub data: Vec<u8>,
}

impl Fragment {
    pub fn encode(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(4 + self.data.len());
        buf.extend_from_slice(&self.id.to_be_bytes());
        buf.push(self.index);
        buf.push(self.total);
        buf.extend_from_slice(&self.data);
        buf
    }

    pub fn decode(data: &[u8]) -> Option<Self> {
        if data.len() < 4 {
            return None;
        }
        
        let id = u16::from_be_bytes([data[0], data[1]]);
        let index = data[2];
        let total = data[3];
        let frag_data = data[4..].to_vec();
        
        Some(Self {
            id,
            index,
            total,
            data: frag_data,
        })
    }
}

pub struct Fragmenter {
    next_id: u16,
}

impl Fragmenter {
    pub fn new() -> Self {
        Self { next_id: 0 }
    }

    pub fn fragment(&mut self, data: &[u8]) -> Vec<Fragment> {
        if data.len() <= MAX_FRAG_SIZE {
            return vec![Fragment {
                id: self.next_id,
                index: 0,
                total: 1,
                data: data.to_vec(),
            }];
        }

        let id = self.next_id;
        self.next_id = self.next_id.wrapping_add(1);

        let total = ((data.len() + MAX_FRAG_SIZE - 1) / MAX_FRAG_SIZE) as u8;
        let mut fragments = Vec::new();

        for (i, chunk) in data.chunks(MAX_FRAG_SIZE).enumerate() {
            fragments.push(Fragment {
                id,
                index: i as u8,
                total,
                data: chunk.to_vec(),
            });
        }

        fragments
    }
}

impl Default for Fragmenter {
    fn default() -> Self {
        Self::new()
    }
}

struct ReassemblyEntry {
    fragments: HashMap<u8, Vec<u8>>,
    total: u8,
    last_update: Instant,
}

pub struct Reassembler {
    entries: HashMap<u16, ReassemblyEntry>,
}

impl Reassembler {
    pub fn new() -> Self {
        Self {
            entries: HashMap::new(),
        }
    }

    pub fn add_fragment(&mut self, frag: Fragment) -> Option<Vec<u8>> {
        self.cleanup_expired();

        let entry = self.entries.entry(frag.id).or_insert_with(|| ReassemblyEntry {
            fragments: HashMap::new(),
            total: frag.total,
            last_update: Instant::now(),
        });

        entry.fragments.insert(frag.index, frag.data);
        entry.last_update = Instant::now();

        if entry.fragments.len() == entry.total as usize {
            // All fragments received
            let mut result = Vec::new();
            for i in 0..entry.total {
                if let Some(data) = entry.fragments.get(&i) {
                    result.extend_from_slice(data);
                }
            }
            self.entries.remove(&frag.id);
            Some(result)
        } else {
            None
        }
    }

    fn cleanup_expired(&mut self) {
        let now = Instant::now();
        self.entries.retain(|_, entry| {
            now.duration_since(entry.last_update) < FRAG_TIMEOUT
        });
    }
}

impl Default for Reassembler {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_fragmentation() {
        let mut fragmenter = Fragmenter::new();
        let data = vec![0u8; 3000];
        
        let fragments = fragmenter.fragment(&data);
        assert!(fragments.len() > 1);
        
        let mut reassembler = Reassembler::new();
        let mut result = None;
        
        for frag in fragments {
            result = reassembler.add_fragment(frag);
        }
        
        assert_eq!(result, Some(data));
    }
}
